package org.NooLab.itexx.storage;

import java.sql.Connection;
import java.sql.DriverManager;

 
import org.NooLab.utilities.logging.PrintLog;
import org.h2.jdbc.JdbcConnection;

import com.iciql.Db;



/**
 * 
 * 
 *
 */
public class DbConnector {

	Connection connection;
	// implemented by x-DataBase classes: it provides the user pool ?
	ConnectorClientIntf connectorClient;
	int maxWaitingTime = 10000;
	
	 
	
	public DbConnector (ConnectorClientIntf client){
		
	}
	
	/**
	 * 
	 * this provides a connection with customized time out
	 * 
	 * it is NOT static!! since we need different instances to different databases !!
	 * @return 
	 * @throws ClassNotFoundException 
	 */
	public Connection getConnection( String url, DbLogin login ) throws Exception{
		
		
		long now,startTime;;
		int result = -1;
		
		JdbcConnection jc;
		
		Class h2Driver = Class.forName("org.h2.Driver");
	
		try{
		
			startTime = System.currentTimeMillis() ;
			
			int z=0;
			
			while ((result>= -4) && (result<0) && (z<20)){
				
				
				try{
					
					
					if (result== -3){
						// msg that process is locked, but that we are waiting for ...
					}
					now = System.currentTimeMillis() ;
					if (now-startTime > maxWaitingTime){
						result = -5 ;	
					}

					if (connection ==null){
						result = -3;
						
						//jc = new JdbcConnection(password, null);
						connection = DriverManager.getConnection( url, login.user, login.password);
						
					}

					// if it is locked by another user, try the next one, [...] then wait 
					// for the allowed period before raising the exception (-5)
					// By default, for each db we provide 10 users for concurrent access

					if (connection!=null){
						result = 0;
						break;
					}
					result = -3;
					
				}catch(Exception e){
					PrintLog.Delay(500) ;
					z++;
				}	
				
			} // any user available
			
			
			
		}catch(Exception e){
			e.printStackTrace();
		}
		
		if (result!=0){
			connection = null;
		}
		return connection;
		
	}
	
}
